﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

using m4aSharp;

namespace m4Console
{
    public partial class m4Form : Form
    {
        public m4Form()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog open = new OpenFileDialog())
            {
                open.Filter = "MPEG 4 audio files (*.m4a)|*.m4a|All files (*.*)|*.*";
                if (open.ShowDialog(this) != System.Windows.Forms.DialogResult.Cancel)
                    Open(open.FileName);
            }
        }

        private void Open(string path)
        {
            pictureBox1.Image = null;
            listView1.Items.Clear();
            treeView1.Nodes.Clear();

            Text = path;      
            LoadTags(path);
            LoadAtoms(path);
        }

        private void LoadTags(string path)
        {
            m4aTags tags = new m4aTags(path);
            tags.Load();

            foreach (KeyValuePair<string, object> pair in tags.Tags)
            {
                ListViewItem item = new ListViewItem(pair.Key);
                item.SubItems.Add(pair.Value.ToString());
                listView1.Items.Add(item);
            }  
        }

        private void LoadAtoms(string path)
        {
            m4aFile file = new m4aFile(path);
            file.Load();

            foreach (Atom atom in file.Atoms.Values)
                AddNodes(atom, treeView1.Nodes);

            Atom cover = file.GetAtom("moov.udta.meta.ilst.covr.data");
            if (cover != null)
                pictureBox1.Image = (Image)cover.InterpretData();
        }

        private void AddNodes(Atom atom, TreeNodeCollection parentCollection)
        {
            string text = atom.Name;
            if (atom.Data != null)
                text += string.Format(" ({0})", atom.InterpretData().ToString());

            TreeNode node = new TreeNode(text);

            foreach (Atom child in atom.Atoms)
                AddNodes(child, node.Nodes);

            parentCollection.Add(node);
        }
    }
}
